package com.gitee.wsl.ext.bitcode


/** Calculates the byte length of the variable int */
fun Byte.calculateVarByteLength(): Int {
    val asInt = this.toInt()
    return when {
        asInt and (0xff shl 7) == 0 -> 1
        else -> 2
    }
}


/** Calculates the byte length of the variable int */
fun Int.calculateVarByteLength(): Int = when {
    this and (Int.MAX_VALUE shl 7) == 0 -> 1
    this and (Int.MAX_VALUE shl 14) == 0 -> 2
    this and (Int.MAX_VALUE shl 21) == 0 -> 3
    this and (Int.MAX_VALUE shl 28) == 0 -> 4
    else -> 5
}


/** Calculates the byte length of the variable unsigned int */
fun UInt.calculateVarByteLength(): Int = when {
    this and (UInt.MAX_VALUE shl 7) == 0u -> 1
    this and (UInt.MAX_VALUE shl 14) == 0u -> 2
    this and (UInt.MAX_VALUE shl 21) == 0u -> 3
    this and (UInt.MAX_VALUE shl 28) == 0u -> 4
    else -> 5
}


/** Calculates the byte length of the variable int */
fun Long.calculateVarByteLength(): Int = when {
    this and (Long.MAX_VALUE shl 7) == 0L -> 1
    this and (Long.MAX_VALUE shl 14) == 0L -> 2
    this and (Long.MAX_VALUE shl 21) == 0L -> 3
    this and (Long.MAX_VALUE shl 28) == 0L -> 4
    this and (Long.MAX_VALUE shl 35) == 0L -> 5
    this and (Long.MAX_VALUE shl 42) == 0L -> 6
    this and (Long.MAX_VALUE shl 49) == 0L -> 7
    this and (Long.MAX_VALUE shl 56) == 0L -> 8
    this and (Long.MAX_VALUE shl 63) == 0L -> 9
    else -> 10
}


/** Calculates the byte length of the variable int */
fun ULong.calculateVarByteLength(): Int = when {
    this and (ULong.MAX_VALUE shl 7) == 0uL -> 1
    this and (ULong.MAX_VALUE shl 14) == 0uL -> 2
    this and (ULong.MAX_VALUE shl 21) == 0uL -> 3
    this and (ULong.MAX_VALUE shl 28) == 0uL -> 4
    this and (ULong.MAX_VALUE shl 35) == 0uL -> 5
    this and (ULong.MAX_VALUE shl 42) == 0uL -> 6
    this and (ULong.MAX_VALUE shl 49) == 0uL -> 7
    this and (ULong.MAX_VALUE shl 56) == 0uL -> 8
    this and (ULong.MAX_VALUE shl 63) == 0uL -> 9
    else -> 10
}


/** Calculates the byte length of the variable int */
fun Short.calculateVarByteLength(): Int {
    val asInt = this.toInt()
    return when {
        asInt and (0xffff shl 7) == 0 -> 1
        asInt and (0xffff shl 14) == 0 -> 2
        else -> 3
    }
}


/** Calculates the byte length of the variable int with extra info */
fun Int.calculateVarIntWithExtraInfoByteSize(): Int = when {
    this and (Int.MAX_VALUE shl 4) == 0 -> 1
    this and (Int.MAX_VALUE shl 11) == 0 -> 2
    this and (Int.MAX_VALUE shl 18) == 0 -> 3
    this and (Int.MAX_VALUE shl 25) == 0 -> 4
    else -> 5
}


/** Calculates the byte length of the variable int with extra info */
fun UInt.calculateVarIntWithExtraInfoByteSize(): Int = when {
    this and (UInt.MAX_VALUE shl 4) == 0u -> 1
    this and (UInt.MAX_VALUE shl 11) == 0u -> 2
    this and (UInt.MAX_VALUE shl 18) == 0u -> 3
    this and (UInt.MAX_VALUE shl 25) == 0u -> 4
    else -> 5
}